package com.team3.ecommerce.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.team3.ecommerce.domain.*;
import com.team3.ecommerce.mapper.CommInOrderMapper;
import com.team3.ecommerce.mapper.CommodityMapper;
import com.team3.ecommerce.mapper.OrderMapper;
import com.team3.ecommerce.mapper.UserInfoMapper;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImp implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private CommInOrderMapper commInOrderMapper;
    @Autowired
    private ShoppingCartService shoppingCartService;


    @Override
    public Order getOrder(String id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        if (order.getOrderStatus().equals("unpaid")){
            queryPayment(id);
            order = orderMapper.selectByPrimaryKey(id);
        }
        return order;
    }

    @Override
    public List<CommInOrder> getCommListInOrder(String order_uid) {
        CommInOrderExample example = new CommInOrderExample();
        example.or().andOrderUidEqualTo(order_uid);
        return commInOrderMapper.selectByExample(example);
    }

    @Override
    public Order newOrder(UserInfo userInfo) {
        Order order = new Order();
        order.setOrderUid(UUID.randomUUID().toString().replace("-", "").toLowerCase());
        order.setUserUid(userInfo.getUserUid());
        order.setOrderPlaceTime(new Timestamp(System.currentTimeMillis()));
        order.setOrderRecName(userInfo.getRecName());
        order.setOrderRecAddress(userInfo.getRecAddress());
        order.setOrderRecPhone(userInfo.getRecPhone());
        order.setOrderStatus("placed");
        orderMapper.insert(order);
        return order;
    }

    @Override
    public Order insertCommodity(String order_uid, String comm_id, int num) {
        CommInOrder commInOrder = new CommInOrder();
        commInOrder.setCommQuantity(num);
        commInOrder.setCommUid(comm_id);
        commInOrder.setOrderUid(order_uid);
        commInOrder.setCommPrice(commodityMapper.selectByPrimaryKey(comm_id).getCommPrice());//将下单时商品价格记录在commInOrder表中
        commInOrderMapper.insert(commInOrder);
        Order order = orderMapper.selectByPrimaryKey(order_uid);
        float totalPrice = 0;
        for (CommInOrder i : getCommListInOrder(order_uid)) {
            totalPrice += commodityMapper.selectByPrimaryKey(i.getCommUid()).getCommPrice() * i.getCommQuantity();//计算订单中商品总价
        }
        order.setOrderTotalPrice(totalPrice);
        orderMapper.updateByPrimaryKey(order);
        return order;
    }

    @Override
    public Order makeNewOrderFromCart(UserInfo userInfo) {
        Order newOrder = newOrder(userInfo);
        List<ShoppingCartItem> shoppingCartItemList = shoppingCartService.getUserShoppingCart(userInfo.getUserUid());
        for (int i = 0; i < shoppingCartItemList.size(); i++) {
            ShoppingCartItem v = shoppingCartItemList.get(i);
            if (v.getItemChecked().equals("true")) {
                newOrder = insertCommodity(newOrder.getOrderUid(), v.getCommUid(), v.getCommQuantity());
            }
        }
        return newOrder;
    }

    @Override
    public String getPaymentPage(String order_uid, String returnUrl) {
        Order order = getOrder(order_uid);
        //这个AlipayClient其实不用每次都new，可以改成component
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016101000653462",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC2bgwJvubS+fcD7CrKxofZZZyRIPXDrQLt1pjkByzyPVWHLTIIg2/lOziDrQ8KZi7Rb+m9n3gZ5um1oYeO3pz49iNoK4iBOW2YU4Yt/SGPPYsajaPUuv1kj3MEtuH8r9ayn7ZNIj6wdJirvIzRRw2sf3CWrWq2CQC0q0uQs2gUAyjMHC37FQxsfh2vTmSD5NsOtA2QZ0MzEXKnAp8k9SzMlj7cz00IttIB2KunrzRP98uugBquwTSoiwg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tWdibHnLuZ5p3jY9I76191rpLLEiqdyKp1u6sz2EtrIIGzLK9efFibTtEL/sKHNU/eoIyGUXt+faed5AoGAO1jD6YfeK5MnMxAgok53WTA5O8CPPsD+vipXPjl18SDzXM2IcUYXHsm4LCHljBbKTCha5dq7Rsvg5v9HKWgvYBjh4jW6TnCkRbHOgajJHZ5fIcrLYcKy4Fi4eyvfrt6iL25HJa5hf5ZtBXkzDP2rIRViJj7MsInq6zxoO+QaR9k=",
                "JSON",
                "utf-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq6SI4M64psn//Xo8RC2oSwXM3fKOasHmYIFN9uB/ac1cOP2B66tJyzZoF7pMUBilXj3c7iIdVRHYoof6HuIHNLZD/Y6hWUjsKJP83maG4Z/iQK9+Xv27zByzHmuCprP2NkLBRwOw/KgXs12IdsiafCmvP2uxCXrhftb1PDFCCgi/B+FC4fqL5gpZL/+GPcPQitusFv9ibhct4FHdI3FT3PI5zLkB5tOWG5+ZSQugvIDvl9pXD7iE7IVr84LVTvWTEKRHT2qBAemAcn+Erjd96kuCdAxVShM41G1waTTnB/w/Yijum6yGRugwa8ifM70hz7SzqxtcSjOx9//ApCQs9wIDAQAB",
                "RSA2"); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl(returnUrl);//在公共参数中设置回跳地址
        //alipayRequest.setNotifyUrl("http://f254n60602.wicp.vip:39507/order/alipayAsyncPost");
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":" + "\"" + order_uid + "\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":" + "\"" + order.getOrderTotalPrice() + "\"," +
                "    \"subject\":" + "\"" + "向Team3电子商务商城付款" + "\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"" +
                "  }");//填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        order.setOrderStatus("unpaid");
        orderMapper.updateByPrimaryKey(order);
        return form;
    }

    @Override
    public void queryPayment(String order_uid) {
        //这个AlipayClient其实不用每次都new，可以改成component
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016101000653462",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC2bgwJvubS+fcD7CrKxofZZZyRIPXDrQLt1pjkByzyPVWHLTIIg2/lOziDrQ8KZi7Rb+m9n3gZ5um1oYeO3pz49iNoK4iBOW2YU4Yt/SGPPYsajaPUuv1kj3MEtuH8r9ayn7ZNIj6wdJirvIzRRw2sf3CWrWq2CQC0q0uQs2gUAyjMHC37FQxsfh2vTmSD5NsOtA2QZ0MzEXKnAp8k9SzMlj7cz00IttIB2KunrzRP98uugBquwTSoiwg7DkHY6T2+qUSPbHHU2eOSQWrqgW7CTRInOWOwK1PxtZcrji+aA7Dj7dA1dCWtoQNk9LkUK+KuOSd4R1WsMtXHdlgyvlnvAgMBAAECggEAf+KJQdO3kDJ2vSMzpE6kMPwQU5SddHy2TvBe4Ys+MNpaOJawOlOZf0KSjYwlvQ6Ax4UCgFFoKhA7yX3gv4DC3av+iinqWVxevaffqiGHAxkLiKO+M4SZ2YLOCIIDzdWeVj2r2EqnU5+I3usgdByxMzlrPdV3twB8pCpooJmD3nJgNhTQnOUVawWAc0EZIgxUDqlhAE+55Hk6jxzUhpEOcOwO4HUQqHmgvwg2Tgb4cQx6wBC3ZozXryYfFtuW2lh3wvqsmPI6niswof7jHeI0nBZJ/WzW3iKA8Zaj5ITcIdEtDC3iIkndfSFD367BDnKBMgbUdDJbT4A12/R9Zqxl4QKBgQDtXZEWZr/DQ165cMMAuxPHym3zqBB+6BuwdsMQObQVLm4L+k3fu7AhJmq8JuuabSZZepOhRzHYU40fdmfvSuT6qqn7x4BYRX35RWej6MKG769lQVpJo0hPIWCS3rTpPW4qBmB9DdKHdxRp3HIpRg3U8C+bWDcIZ5OEyomc5K1FpwKBgQDEwGqJAnbzl7n9p7TVfxOeT5mKtrsTwHvGwXyTjBrfSFSfLxz0BJuQMGDmc8vBmteIOKbm9XvStXLNbN83eVjv7qNx5/3SbwTRDSPtNLDiDzQXkxXre7YInRHc7nCJC+bgcss4NNwd3h0PZF1sl9ARCcORhkx2ZzTSvgjRwS3ieQKBgQDq9ejNvO3rsr+MXvOYwJaG+Xm3bFDP3qCyIA1c/VGmeexTDPWTF630UpvrHbewiIUio7SJO/k6QxJ553Jgq8lX3CIhak1Ak6FsY2iBFsGgYphDadqe8/N66PY4zB1WmAl5rhBLGaihkZ1yYNXcx0yf0RW+9yaaujSLiRWJac+fFwKBgApISAkLAO5wEn9IIXI65uqSHGMcc6BvochcWkdXvhvHKuz6yFeUWhDqBlZk3NQsZHExDL/rOmJjqzFDLFM420YGwbH1PtWdibHnLuZ5p3jY9I76191rpLLEiqdyKp1u6sz2EtrIIGzLK9efFibTtEL/sKHNU/eoIyGUXt+faed5AoGAO1jD6YfeK5MnMxAgok53WTA5O8CPPsD+vipXPjl18SDzXM2IcUYXHsm4LCHljBbKTCha5dq7Rsvg5v9HKWgvYBjh4jW6TnCkRbHOgajJHZ5fIcrLYcKy4Fi4eyvfrt6iL25HJa5hf5ZtBXkzDP2rIRViJj7MsInq6zxoO+QaR9k=",
                "JSON",
                "utf-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq6SI4M64psn//Xo8RC2oSwXM3fKOasHmYIFN9uB/ac1cOP2B66tJyzZoF7pMUBilXj3c7iIdVRHYoof6HuIHNLZD/Y6hWUjsKJP83maG4Z/iQK9+Xv27zByzHmuCprP2NkLBRwOw/KgXs12IdsiafCmvP2uxCXrhftb1PDFCCgi/B+FC4fqL5gpZL/+GPcPQitusFv9ibhct4FHdI3FT3PI5zLkB5tOWG5+ZSQugvIDvl9pXD7iE7IVr84LVTvWTEKRHT2qBAemAcn+Erjd96kuCdAxVShM41G1waTTnB/w/Yijum6yGRugwa8ifM70hz7SzqxtcSjOx9//ApCQs9wIDAQAB",
                "RSA2"); //获得初始化的AlipayClient
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();//创建API对应的request
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"" + order_uid + "\"" +
                "  }");
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(alipayRequest);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.getCode().equals("40004"))
            return;
        if (response.getTradeStatus() == null)
            return;
        if (response.getTradeStatus().equals("TRADE_SUCCESS")) {
            Order order = orderMapper.selectByPrimaryKey(order_uid);
            order.setOrderStatus("paid");
            order.setOrderPaymentTime(response.getSendPayDate());
            orderMapper.updateByPrimaryKey(order);
        }
    }

    @Override
    public List<Order> searchOrdersByUserWithinPage(UserInfo userInfo,int offset,int pageSize) {
        OrderExample example = new OrderExample();
        example.or().andUserUidEqualTo(userInfo.getUserUid());
        example.setOrderByClause(" order_place_time desc ");
        example.setDistinct(true);
        example.setPageIndex(offset);
        example.setPageSize(pageSize);
        return orderMapper.selectByExample(example);
    }

    @Override
    public int orderSizeOfUser(UserInfo userInfo) {
        OrderExample example = new OrderExample();
        example.or().andUserUidEqualTo(userInfo.getUserUid());
        example.setDistinct(true);
        return orderMapper.selectByExample(example).size();
    }
}
